import qs from 'qs'
import store from '@/store'

const getItem = (key) => {
  const query = store.getters.queryString
  if (query[key] && typeof (query[key]) == 'string') {
    let result = query[key].replace(/ /g, '\+')
    if (key === 'data') {
      result = handleData(result)
    }
    localStorage.setItem(key, result)
  }

  return localStorage.getItem(key)
}

const getters = {
  userName: state => state.app.userName,
  tabBarHeight: state => state.app.tabBarHeight,
  navBarHeight: state => state.app.navBarHeight,
  queryString: () => {
    let url = ''
    if (location.hash.indexOf('data') !== -1) {
      url = location.hash
    } else {
      url = location.search
    }
    // const newUrl = url.split('?')[1] ? ? ''
    const newUrl = url.split('?')[1] ? url.split('?')[1] : ''
    return qs.parse(newUrl)
  },
  data: () => getItem('data'),
  token: () => getItem('token')
}

function handleData(str) {
  let newStr = window.atob(str)
  let result = newStr.match(/\|USRNBR=([^\|]*)\|/)
  if (result) {
    let ystID = result[1]
    // newStr += `|ystID=${ystID}`
    newStr = JSON.stringify({
      ystID: ystID
    })
  }
  return window.btoa(newStr)
}

export default getters
